﻿using StudentInfoSystem.Core.Interfaces;
using StudentInfoSystem.Core.Models;
using StudentInfoSystem.UI.Services;
using StudentInfoSystem.UI.Views.Component;
using StudentInfoSystem.UI.Views.Pages;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;

namespace StudentInfoSystem.UI.ViewModels;

public class MainWindowViewModel : INotifyPropertyChanged
{
    private Dictionary<string, UserControl> _pageCache = null!;
    private UserControl _currentPage = null!;
    private readonly IStudentService _studentService;
    private List<Student> _allStudents;

    public event PropertyChangedEventHandler? PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public MainWindowViewModel()
    {
        // 获取学生服务实例
        _studentService = Bootstrapper.AppHost.Services.GetRequiredService<IStudentService>();
        
        _pageCache = [];
        _allStudents = new List<Student>();
        
        // 监听主题和背景图片变化
        AppSettings.Instance.PropertyChanged += (s, e) =>
        {
            if (e.PropertyName == nameof(AppSettings.IsDarkTheme) ||
                e.PropertyName == nameof(AppSettings.IsBackgroundImageEnabled))
            {
                OnPropertyChanged(nameof(IsBackgroundVisible));
            }
        };
        
        NavigationInit();
        LoadData();
    }

    public UserControl CurrentPage
    {
        get => _currentPage;
        set
        {
            if (_currentPage != value)
            {
                _currentPage = value;
                OnPropertyChanged();
            }
        }
    }

    // 计算属性：背景是否可见
    public bool IsBackgroundVisible => AppSettings.Instance.IsBackgroundImageEnabled;

    // ============================= 私有成员函数 =============================
    private void NavigationInit()
    {
        // 初始化所有页面
        _pageCache = new Dictionary<string, UserControl>
        {
            { "StudentListButton", new StudentListView() },
            { "StatisticsButton", new StatisticsView() },
            { "SettingsButton", new SettingsView(AppSettings.Instance) },
        };

        ExecuteNavigation("StudentListButton");
    }
    
    // 加载数据
    private void LoadData()
    {
        _allStudents = _studentService.GetAll().ToList();

        if (CurrentPage is StudentListView studentListView &&
            studentListView.DataContext is StudentListViewModel studentListViewModel)
        {
            studentListViewModel.RefreshData(_allStudents);
        }
    }

    // ============================= 公共函数 =============================
    public void ExecuteNavigation(string pageKey)
    {
        if (!_pageCache.TryGetValue(pageKey, out var page))
        {
            // 创建页面实例，防止页面丢失
            page = pageKey switch
            {
                "StudentListButton" => new StudentListView(),
                "StatisticsButton" => new StatisticsView(),
                "SettingsButton" => new SettingsView(AppSettings.Instance),
                _ => new StudentListView() // 使用专门的错误页面
            };
            _pageCache[pageKey] = page;

            // 显示通知窗口
            ShowPageNotFoundAlert(pageKey);
        }
        CurrentPage = page;
        
        // 导航到新页面时刷新数据
        if (pageKey == "StudentListButton" || pageKey == "StatisticsButton")
        {
            LoadData();
        }
    }
    
    // 重新加载数据
    public void ReloadData()
    {
        LoadData();

        // 同时刷新统计视图数据
        RefreshStatisticsView();
    }

    // ============================= 私有辅助函数 =============================
    private static void ShowPageNotFoundAlert(string pageKey)
    {
        var pageString = pageKey switch
        {
            "StudentListButton" => "学生列表",
            "StatisticsButton" => "统计",
            "SettingsButton" => "设置",
            _ => "未找到页面"
        };

        MessageBox.Show(
            $"找不到请求的页面: {pageString}\n已加载默认页面作为替代",
            "页面加载问题",
            MessageBoxButton.OK,
            MessageBoxImage.Warning
        );
    }
    // 新增方法：刷新统计视图
    private void RefreshStatisticsView()
    {
        if (_pageCache.TryGetValue("StatisticsButton", out var statPage) &&
            statPage is StatisticsView statisticsView)
        {
            if (statisticsView.DataContext is StatisticsViewModel statisticsViewModel)
            {
                // 调用统计视图的刷新命令
                statisticsViewModel.RefreshCommand.Execute(null);
            }
        }
    }
}